package com.yungu.swift.admin.base;

import com.yungu.swift.admin.route.helper.JwtHelper;
import com.yungu.swift.base.model.admin.AdminParam;
import com.yungu.swift.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RequestBody;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;

/**
 * @author : cuixiuyin
 * @date : 2019/6/13
 */
@Slf4j
@ControllerAdvice
public class RequestBodyAdvice implements org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice {

    @Override
    public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return methodParameter.hasParameterAnnotation(RequestBody.class);
    }

    @Override
    public Object handleEmptyBody(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        if (o == null) {
            o = new AdminParam();
        }
        token2Body(o, httpInputMessage);
        return o;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
        return httpInputMessage;
    }

    @Override
    public Object afterBodyRead(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        token2Body(o, httpInputMessage);
        return o;
    }


    /**
     * 解析 token 信息，将 token 转换成 request body
     *
     * @param o
     * @param httpInputMessage
     */
    private void token2Body(Object o, HttpInputMessage httpInputMessage) {
        HttpHeaders headers = httpInputMessage.getHeaders();
        List<String> list = headers.get(GatewayHeader.accessToken);
        if (CollectionUtils.isNotEmpty(list)) {
            String accessToken = list.get(0);
            try {
                AdminParam adminParam = JsonUtils.readValue(JwtHelper.parseJWT(accessToken), AdminParam.class);
                BeanUtils.copyProperties(adminParam, o);
            } catch (IOException e) {
                log.error("RequestBodyAdvice afterBodyRead readValue error.accessToken:{}", accessToken, e);
            }
        }
    }
}
